package net.sddf.system.bank.web;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sddf.system.bank.business.AgencyBidService;
import net.sddf.system.bank.business.BalanceDetailsService;
import net.sddf.system.bank.business.BankService;
import net.sddf.system.bank.business.BorrowRecordService;
import net.sddf.system.bank.business.model.dto.BankCardRequestDto;
import net.sddf.system.bank.business.model.vo.BankCardVo;
import net.sddf.system.bank.business.model.vo.BorrowRecordStatusBankVO;
import net.sddf.system.bank.common.constant.PreTransactionCode;
import net.sddf.system.bank.common.result.Result;
import net.sddf.system.bank.common.util.EncryptUtil;
import net.sddf.system.bank.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * 银行托管系统
 */
@Slf4j
@RestController
@Api(tags = "银行托管系统API")
public class BankController {
	@Autowired
	private BankService bankService;
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private BorrowRecordService borrowRecordService;
	@Autowired
	private AgencyBidService agencyBidService;
	@Autowired
	private BalanceDetailsService balanceDetailsService;

	/**
	 * 银行托管系统用户绑定
	 */
	@ApiOperation("银行托管系统用户绑定")
	@PostMapping(value = "/bank/user")
	public String bindUserCard(BankCardRequestDto bankCardRequestDto) {
		log.info("bankCardRequestDto={}",bankCardRequestDto);
		bankService.createUser(bankCardRequestDto);

		String callbackUrl = "http://localhost:5500/bank/access/receive";
		ResponseEntity<String> entity =
				restTemplate.postForEntity(callbackUrl, bankCardRequestDto, String.class);
		log.info("银行托管系统回调结果：{}",entity);
		return entity.getBody();
	}

	@ApiOperation("同步借款项目")
	@GetMapping(value = "/service",params = "serviceName=SYNC_BORROW_RECORD")
	public DepositoryResponse<CreateProjectResponse> syncBorrowRecord(
			@RequestParam String reqData) {
		log.info("银行托管，请求数据：" + reqData);
		CreateProjectResponse projectResponse =
				borrowRecordService.syncBorrowRecord(reqData);
		return new DepositoryResponse<>(projectResponse);
	}

	@ApiOperation("获取机构账户余额信息")
	@GetMapping("/bid/balance/{userCode}")
	public BalanceDetailsDTO getBalanceDetails(@PathVariable("userCode") String userCode) {
		BalanceDetailsDTO balanceDetailsDTO = bankService.getBalanceDetails(userCode);
		return balanceDetailsDTO;
	}

	@ApiOperation("预授权处理")
	@GetMapping(value = "/service", params = "serviceName=AGENCY_BID")
	public DepositoryResponse<UserAutoPreTransactionResponse> authorizeAutoPreTransaction(
			@RequestParam(required = false)  String platformNo,
			@RequestParam(required = false)  String reqData) {
		UserAutoPreTransactionResponse transactionResponse =
				new UserAutoPreTransactionResponse();

		log.info("银行托管系统，接收请求数据，数据Base64编码");
		String decodeUrlData = EncryptUtil.decodeURL(reqData);
		String decodeReqData = EncryptUtil.decodeUTF8StringBase64(decodeUrlData);
		log.info("银行托管系统，接收请求数据，数据Base64解码后的字符串：{}",decodeReqData);

		BankBidDTO bankBidDTO =
				JSON.parseObject(decodeReqData, BankBidDTO.class);

		//判断bizType
		if (PreTransactionCode.TENDER.getCode().equals(bankBidDTO.getBizType())) {
			//用户投资申购
			transactionResponse = agencyBidService.autoPreTransactionForTender(bankBidDTO);
		} else if (PreTransactionCode.REPAYMENT.getCode().equals(bankBidDTO.getBizType())) {
			//还款确认冻结金额
			log.info("还款确认冻结金额");
			balanceDetailsService.autoPreTransactionForRepayment(bankBidDTO);
		}
		return new DepositoryResponse<>(transactionResponse);
	}

	@ApiOperation(value = "放款确认")
	@GetMapping(value = "/service", params = "serviceName=CONFIRM_LOAN")
	public DepositoryResponse<ConfirmLoanResponse> confirmLoan(
			@RequestParam(required = false) String reqData) {
		log.info("放款确认,reqData:{}",reqData);
		ConfirmLoanResponse confirmLoanResponse = agencyBidService.confirmLoan(reqData);
		return new DepositoryResponse<>(confirmLoanResponse);
	}

	@ApiOperation("更改借款项目状态")
	@GetMapping(value = "/service", params = "serviceName=UPDATE_BORROW_STATUS")
	public Result updateBorrowRecordStatus(
			@RequestParam(required = false) String reqData) {
		BorrowRecordStatusBankVO brsVO =
				borrowRecordService.updateBorrowRecordStatus(reqData);
		log.info("银行托管系统-更改借款状态,返回数据：{}",brsVO);
		return Result.ok(brsVO);
	}

	@ApiOperation(value = "还款确认", notes = "将还款预处理冻结的资金划转至投资人账户")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "serviceName", value = "接口名称", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "platformNo", value = "接入平台编号", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "signature", value = "针对请求数据reqData的签名", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "reqData", value = "业务数据报文，JSON 格式", required = true, dataType = "String", paramType = "query"),})
	@GetMapping(value = "/service", params = "serviceName=CONFIRM_REPAYMENT")
	public DepositoryResponse<ConfirmRepaymentResponse> confirmRepayment(@RequestParam String serviceName,
																		 @RequestParam String platformNo, @RequestParam String signature, @RequestParam String reqData) {
		ConfirmRepaymentResponse repaymentResponse = new ConfirmRepaymentResponse();
		return new DepositoryResponse<>(repaymentResponse);
	}
}
